package com.swg.seckill.config;

import com.swg.seckill.pojo.User;
import com.swg.seckill.service.IUserService;
import com.swg.seckill.utils.CookieUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

@Component
public class UserArgumentResolver implements HandlerMethodArgumentResolver {

    @Autowired
    private IUserService iUserService;

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        Class<?> parameterType = parameter.getParameterType();
        return parameterType == User.class;
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        HttpServletRequest Request = webRequest.getNativeRequest(HttpServletRequest.class);
        System.out.println("进入了");
        String userTicket = CookieUtil.getCookieValue(Request, "userTicket", false);
        if(StringUtils.isEmpty(userTicket)){
            System.out.println("为空");
            return  null;
        }

        return iUserService.getUserByCookie(userTicket);
    }
}
